import 'package:flutter/cupertino.dart';
import 'package:logger/logger.dart';

import '../../api/api_salary.dart';
import '../../api/models/expenses_model.dart';
import '../../core/app_initializer.dart';
import '../../storage/app_cache_manager.dart';
import '../../utils/time_utils.dart';

class ConsumptionCalendarViewModel extends ChangeNotifier {
  final Logger logger = AppInitializer.logger;

  List<ExpensesAssignment> schedules = [];

  // 用 Map 存储日历数据
  Map<DateTime, List<ExpensesAssignment>> assignments = {};

  Future<void> fetchSchedules({DateTime? startDate, DateTime? endDate}) async {
    startDate ??= TimeUtils.getMonthStart();
    endDate ??= TimeUtils.getMonthEnd();

    final cacheKey = "schedules-${startDate.year}-${startDate.month}";

    // 1. 先尝试从缓存读取
    try {
      final cached =
          await AppCacheManager.get<List<Map<String, dynamic>>>(cacheKey);
      if (cached != null) {
        logger.i("Loaded schedules from cache: $cacheKey");

        // 还原成 assignments
        assignments.clear();
        for (var item in cached) {
          final date = DateTime.parse(item['date']);
          assignments.putIfAbsent(date, () => []);
          assignments[date]!.add(ExpensesAssignment.fromJson(item));
        }

        notifyListeners();
        return;
      }

      // 2. 没有缓存 → 请求接口
      var queryBody = {
        "startTime": startDate.toIso8601String(),
        "endTime": endDate.toIso8601String(),
      };

      schedules = await ApiSalary.api.getCheckSchedules(queryBody);

      assignments.clear();
      final cacheData = <Map<String, dynamic>>[];

      assignments.clear();
      for (var s in schedules) {
        final date = DateTime.utc(s.date.year, s.date.month, s.date.day);
        assignments.putIfAbsent(date, () => []);
        assignments[date]!.add(s);

        // 存储到缓存结构
        cacheData.add(s.toJson());
      }

      // 3. 写入缓存（比如缓存 1 小时）
      await AppCacheManager.set<List<Map<String, dynamic>>>(
        cacheKey,
        cacheData,
        ttl: const Duration(hours: 1),
      );

      notifyListeners();
    } catch (e) {
      logger.e('Failed to fetch schedules $e');
    }
  }

  /// 刷新指定月份的数据（清理缓存 + 重新请求）
  Future<void> refreshSchedules(DateTime month) async {
    final startDate = DateTime(month.year, month.month, 1);
    final endDate = DateTime(month.year, month.month + 1, 0);

    final cacheKey = "schedules-${startDate.year}-${startDate.month}";

    // 1. 删除缓存
    await AppCacheManager.remove(cacheKey);

    // 2. 重新请求
    await fetchSchedules(startDate: startDate, endDate: endDate);
  }

  List<ExpensesAssignment> eventsOf(DateTime day) {
    final key = DateTime.utc(day.year, day.month, day.day);
    return assignments[key] ?? [];
  }
}
